/**
 *
 *
 *
 *
 *
 */

package server.modules.sys.controller;

import server.common.annotation.SysLog;
import server.common.utils.R;
import server.modules.sys.dao.SysUserDao;
import server.modules.sys.entity.SysUserEntity;
import server.modules.sys.form.SysLoginForm;
import server.modules.sys.service.SysCaptchaService;
import server.modules.sys.service.SysUserService;
import server.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import server.common.annotation.SysLog;
import server.common.utils.R;
import server.modules.sys.entity.SysUserEntity;
import server.modules.sys.form.SysLoginForm;
import server.modules.sys.service.SysCaptchaService;
import server.modules.sys.service.SysUserService;
import server.modules.sys.service.SysUserTokenService;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 *
 * @author
 */
@RestController
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @GetMapping("/loginInfo")
    public R loginInfo() throws IOException {
        return R.ok().put("info", sysUserService.queryLoginInfo());
    }

    /**
     * 登录
     */
    @SysLog("登录")
    @PostMapping("/sys/login")
    public Map<String, Object> login(@RequestBody SysLoginForm form) throws IOException {
		/*boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return R.error("验证码不正确");
		}*/

        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

        //账号不存在、密码错误
        if (user == null) {
            sysUserService.lambdaUpdate().eq(SysUserEntity::getUserId, getUserId()).set(SysUserEntity::getLoginStatus, 0).update();
            return R.error("账号不正确");
        }

        // 获取token信息
        R r = sysUserTokenService.checkToken(user.getUserId());
        if (null != r) {
            if (r.containsKey("token")) {
                sysUserService.lambdaUpdate().eq(SysUserEntity::getUserId, user.getUserId()).set(SysUserEntity::getLoginStatus, 1).update();
                return r;
            } else {
                if (this.getUser() != null) {
                    if (!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
                        sysUserService.lambdaUpdate().eq(SysUserEntity::getUserId, getUserId()).set(SysUserEntity::getLoginStatus, 0).update();
                        return R.error("登陆状态已超时，请输入正确的密码登陆");
                    }
                }
            }
        }

//
//        if (!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
//            return R.error("密码不正确");
//        }

        //账号锁定
        if (user.getStatus() == 0) {
            sysUserService.lambdaUpdate().eq(SysUserEntity::getUserId, getUserId()).set(SysUserEntity::getLoginStatus, 0).update();
            return R.error("账号已被锁定,请联系管理员");
        }


        //生成token，并保存到数据库
        r = sysUserTokenService.createToken(user.getUserId());

        sysUserService.lambdaUpdate().eq(SysUserEntity::getUserId, user.getUserId()).set(SysUserEntity::getLoginStatus, 1).update();


        return r;
    }


    /**
     * 退出
     */
    @SysLog("登出")
    @PostMapping("/sys/logout")
    public R logout() {
        sysUserTokenService.logout(getUserId());
        sysUserService.lambdaUpdate().eq(SysUserEntity::getUserId, getUserId()).set(SysUserEntity::getLoginStatus, 0).update();

        return R.ok();
    }

}
